package com.huifaapp.mall.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.JsonBean;
import com.huifaapp.mall.bean.JsonFileReader;
import com.huifaapp.mall.bean.PersonalProfileBean;
import com.huifaapp.mall.bean.event.ImageBean;
import com.huifaapp.mall.selectImage.PhoneConfirmActivity;
import com.huifaapp.mall.selectImage.SelectPicMenu;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.view.RoundImageView;
import com.huifaapp.mall.view.titlebar.DatePickerPopWin;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class PersonalProfileActivity extends AppCompatActivity {

    private TextView Cityset;
    private TextView Nameset;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<String> arr=new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private ImageView Imback;
    private TextView Sexset,Birthdayset;
    private ImageView Imset;
    private PersonalProfileBean.DataBean personlist;
    private String city;
    private View changeHeadLayout;
    private RoundImageView roundImageView;
    private String imgurl;
    private TextView personal_profile_phone;
    private TextView tv_person_zanwu;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_profile);

        selectPicMenu = new SelectPicMenu(this);
        selectPicMenu.create();

        initView();

        setListener();
        initJsonData();

    }

    SelectPicMenu selectPicMenu;
    private void setListener() {
        changeHeadLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectPicMenu.show();
            }
        });
        Cityset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPickerView();

            }
        });
        Nameset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PersonalProfileActivity.this, PetnameActivity.class);
                startActivityForResult(intent,1221);
            }
        });
        Sexset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(PersonalProfileActivity.this); //定义一个AlertDialog
                final String[] strarr = {"男","女"};
                builder.setItems(strarr, new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface arg0, int arg1)
                    {
                        String sex = "2";
                        // 自动生成的方法存根
                        if (arg1 == 0) {//男
                            sex = "男";

                        }else {//女
                            sex = "女";

                        }
                        final String finalSex = sex;
                        OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL + "users/managesex")
                                .addParams("sex",sex)
                                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Request request, Exception e) {

                                    }

                                    @Override
                                    public void onResponse(String response) {

                                        Sexset.setText(finalSex);
                                        ToastUtils.showShort("修改成功");

                                    }
                                });

                    }
                });
                builder.show();

            }
        });
        Birthdayset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Birthdayset();
            }
        });




Log.e("个人",ApiManager.BASE_NIUPAI_URL+"users/info"+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this));
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/info")
                //?token=2017121117473013488a1208548b1f422cb1bcbe4fc56c9501&appId=5B489793-3521-4043-95C4-9F98C6B02E47")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    final PersonalProfileBean personalProfileBean = gson.fromJson(response,PersonalProfileBean.class);
                    personlist = personalProfileBean.getData();
                    Sexset.setText(personalProfileBean.getData().getSex());
                    Glide.with(PersonalProfileActivity.this).load(personlist.getUserHeadimg())
                            .asBitmap()
                            .into(roundImageView);
                    Birthdayset.setText(personalProfileBean.getData().getBirth().split(" ")[0]);
                    Cityset.setText(personalProfileBean.getData().getCity());
                    Nameset.setText(personalProfileBean.getData().getUserNickname());
                    personal_profile_phone.setText(personalProfileBean.getData().getPhone());
                    if(personalProfileBean.getData().getTgwId().equals("")){
                        tv_person_zanwu.setText("暂无");
                    }else{
                    tv_person_zanwu.setText(personalProfileBean.getData().getTgwId()+" 复制");
                        tv_person_zanwu.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                ClipboardUtils.copyText(personalProfileBean.getData().getTgwId());
                                Toast.makeText(PersonalProfileActivity.this,"复制成功！",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    personal_profile_phone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    });
                }catch (Exception e){
//                    Toast.makeText(PersonalProfileActivity.this, personalProfileBean., Toast.LENGTH_SHORT).show();
                    Log.e("数据",e.getMessage());
                }
            }
        });
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                city = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);
                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"/users/managecity")
                        .addParams("city",city)
                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                        .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {

                            }

                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
//                           JSONObject jsonObject = null;
//                           jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
                                    if (code.equals("10000"))
                                    {
                                        ToastUtils.showShort("修改成功");
                                        Cityset.setText(city);
                                    }else {
                                        ToastUtils.showShort("修改失败");
                                    }
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        });
                //           Cityset.setText(city);
//                 city = Cityset.getText().toString();
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(15)
                .setOutSideCancelable(false)
                .build();


          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(arr, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private void initView() {
        Cityset = (TextView) findViewById(R.id.city);
        Nameset = (TextView) findViewById(R.id.textnamexg);
        Imback = (ImageView) findViewById(R.id.iv_personal_profile_back);
        Imback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        Sexset = (TextView) findViewById(R.id.personal_profile_sex);
        Birthdayset = (TextView) findViewById(R.id.personal_profile_birthday);
        roundImageView = (RoundImageView) findViewById(R.id.personal_profile_img);
        changeHeadLayout = findViewById(R.id.changeHeadLayout);
        personal_profile_phone= (TextView) findViewById(R.id.personal_profile_phone);
        tv_person_zanwu= (TextView) findViewById(R.id.tv_person_zanwu);
    }


    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份

            arr.add(jsonBean.get(i).getName());
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new  JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1221&& resultCode == 2222) {
            Nameset.setText(data.getStringExtra("name"));
        } else if (resultCode == 2 && data != null) {//相册选择的activity返回的结果
            String path = data.getStringExtra("path");
            try {
                updateAvatar(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }  else if (SelectPicMenu.FLAG_CHOOSE_PHONE == requestCode && resultCode == -1){//拍照之后跳转到的activity
            Intent intent = new Intent(this, PhoneConfirmActivity.class);
            intent.putExtra("path", selectPicMenu.getFileImageName());
            startActivityForResult(intent, 10);
            return;
        } else if (resultCode == PhoneConfirmActivity.RESCODE_PATH && data != null) {//拍照之后跳转到的activity返回的结果
            String imgPath = data.getStringExtra("path");
            try {
                updateAvatar(imgPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 修改头像
     * @param filePath
     */
    private void updateAvatar(String filePath)  {

        Log.e("ffffffffff",filePath);
        //ImageLoader.getInstance().displayImage("file://" + filePath, Imset);
        File file = new File(filePath);
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        final Request request = new Request.Builder()
                .url("http://file.jhjvip.cn:8888/image-server/uploadImage/mall")
                .post(requestBody)
                .build();
        Call call = new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                System.out.println("Request onFailure");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {

                    String json = response.body().string();
                    Log.e("fffff", json);
                    Gson gson = new Gson();
                    ImageBean imageBean = gson.fromJson(json, ImageBean.class);
                    final String image = imageBean.getData().getUrl();
                    Log.e("ninini", image);
                    Log.e("个人资料",ApiManager.BASE_NIUPAI_URL + "users/manageuserHeadImg"+"?userHeadImg="+image+
                            "&token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+
                            "&appId="+AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this));
                    OkHttpUtils.post().
                            url(ApiManager.BASE_NIUPAI_URL + "users/manageuserHeadImg")
                            .addParams("userHeadImg", image)
                            .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                            .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Request request, Exception e) {

                                }

                                @Override
                                public void onResponse(String response) {
//                                    EventBus.getDefault().post(new OrderStatusEventMessage(
//                                            OrderStatusEventMessage.TYPE_RECEIVED,image));

                                    OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/info")
                                            //?token=2017121117473013488a1208548b1f422cb1bcbe4fc56c9501&appId=5B489793-3521-4043-95C4-9F98C6B02E47")
                                            .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                            .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                                            .build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            try {
                                                Gson gson = new Gson();
                                                PersonalProfileBean personalProfileBean = gson.fromJson(response,PersonalProfileBean.class);
                                                personlist = personalProfileBean.getData();
                                                Sexset.setText(personalProfileBean.getData().getSex());
                                                Glide.with(PersonalProfileActivity.this).load(personlist.getUserHeadimg())
                                                        .asBitmap()
                                                        .into(roundImageView);
                                                Birthdayset.setText(personalProfileBean.getData().getBirth().split(" ")[0]);
                                                Cityset.setText(personalProfileBean.getData().getCity());
                                                Nameset.setText(personalProfileBean.getData().getUserNickname());
                                                ////////////////////
                                                personal_profile_phone.setText(personalProfileBean.getData().getPhone());








                                            }catch (Exception e){
                                                Toast.makeText(PersonalProfileActivity.this, "fangwenbudao", Toast.LENGTH_SHORT).show();
                                            }

                                        }
                                    });
                                }
                            });

                } catch (Exception e) {
                    e.printStackTrace();
                }



            }
        });



    }

    private void  Birthdayset(){
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(1890,0,1);
        endDate.set(2017,11,31);


        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(final Date date, View v) {//选中事件回调

                OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/managebirth")
                        .addParams("birth",getTime(date))
                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                        .addParams("appId", AUniqueIdentifier.getDeviceId(PersonalProfileActivity.this))
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {

                            }

                            @Override
                            public void onResponse(String response) {
                                Log.e("SHENGRI",response);
                                Birthdayset.setText(getTime(date));
                                ToastUtils.showShort("xiugaichenggong");
                            }
                        });

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .isCyclic(true)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate,endDate)//起始终止年月日设定
                .setLabel("年","月","日","时","分","秒")//默认设置为年月日时分秒
                .build();
        pvTime.show();
    }

    private String getTime(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

}
